//路由鉴权、项目中路由能不能被访问的权限设置
import router from "@/router";
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import settings from "./settings";
import pinia from './store'
import useUserStore from '@/store/modules/user';
nprogress.configure({showSpinner:false})
let userStore = useUserStore(pinia);

//全局前置守卫
router.beforeEach ( async(to: any, from: any, next: any) => {
  document.title = settings.title  + to.meta.title
  //to:将要访问的路由
  //from:从那个路由来
  //next:路由放行函数
  nprogress.start();
  let token = userStore.token;
  //获取用户名
  let username = userStore.username;
  if(token){
    if(to.path=='/login'){
        next({path:'/'})
    }else{
        if(username){
            next();
        }else{
          try{
            //在守卫发起请求获取信息
            await userStore.userInfo();
            next();
          }catch(e){
            //token过期或用户修改本地token
            await userStore.userLogout();
            next({path:'/login',query:{redirect:to.path}})
          }
            
        }
    }
  }else{
    if(to.path == '/login'){
        next();
    }else{
        next({path:'/login',query:{redirect:to.path}})
    }
  }

});

//全局后置守卫
router.afterEach((to: any, from: any, next: any) => {
  nprogress.done();
});

//1.路由切换进度条功能 --- nprogress
//2.路由鉴权问题（访问权限问题）
//全部路由：首页|数据大屏|404|登录|权限管理（3个子路由）|商品管理（4个字路由）|任意路由

//用户未登录只能访问login界面
//登录成功后不可再访问login
